//
//  APTranslateManager.m
//  AqualPolo
//
//  Created by dong on 2024/5/10.
//

#import "APTranslateManager.h"

@implementation APTranslateManager
static NSString *translateUrl = @"https://translation.googleapis.com/language/translate/v2";

+ (APTranslateManager *)shareInstance{
    static APTranslateManager *shareId = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareId = [[self alloc] init];
    });
    return shareId;
}


- (void)translateText:(NSString *)content toLan:(NSString *)target result:(LYTranslateResultBlock)callBack{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *key = [APUserDataManager shareInstance].googleTranslationKey;
//    [parameters setObject:key forKey:@"key"];
//    [parameters setObject:target forKey:@"target"];
    [parameters setObject:content forKey:@"q"];
//    [parameters setObject:@"text" forKey:@"format"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    AFJSONResponseSerializer *response =  [AFJSONResponseSerializer serializer];
    response.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    manager.responseSerializer = response;
    manager.requestSerializer.timeoutInterval = 30;
//    [manager.requestSerializer clearAuthorizationHeader];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [securityPolicy setAllowInvalidCertificates:YES];
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    LYLog(@"--%@",parameters);
    NSString *url = [NSString stringWithFormat:@"%@?key=%@&target=%@&format=text",translateUrl,key,target];
    LYLog(@"--%@",url);
    [manager POST:url parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LYLog(@"--%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
          APTranslateModel *model = [APTranslateModel modelWithDictionary:responseObject[@"data"]];
          LYLog(@"=translatedText===%@",model.translations);
            if (callBack) {
                callBack(model.translations.firstObject.translatedText);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LYLog(@"%@",error);
        if (callBack) {
            callBack(@"");
        }
    }];

}

  


@end


